package com.lc.zpyh.ui.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.zpyh.R;
import com.lc.zpyh.app.AppActivity;
import com.lc.zpyh.http.glide.GlideApp;
import com.lc.zpyh.http.request.SearchCommodityApi;
import com.lc.zpyh.http.request.SelectCanteenBySchoolIdApi;
import com.lc.zpyh.http.response.SearchCommodityBean;
import com.lc.zpyh.http.response.SelectCanteenBySchoolBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.ui.activity.mine.LoginCodeActivity;
import com.lc.zpyh.ui.activity.supermarket.BusinessActivity;
import com.lc.zpyh.util.BigDecimalUtils;
import com.lc.zpyh.util.CourseUtils;
import com.lc.zpyh.util.SPUtil;
import com.lc.zpyh.view.SearchPopupWindow;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchGoodsActivity extends AppActivity {
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.rl_clear)
    RelativeLayout rlClear;
    @BindView(R.id.rl_search)
    RelativeLayout rlSearch;
    @BindView(R.id.title_bar_txt_right)
    TextView titleBarTxtRight;
    @BindView(R.id.rl_layout_focus)
    RelativeLayout rlLayoutFocus;
    @BindView(R.id.rv_goods_searches)
    RecyclerView rvGoodsSearches;
    @BindView(R.id.check_address)
    TextView checkAddress;
    @BindView(R.id.check_xiaoliang)
    CheckBox checkXiaoliang;
    @BindView(R.id.check_renjun)
    CheckBox checkRenjun;
    @BindView(R.id.ll_top)
    LinearLayout llTop;
    private  int canteenId=0;
    private  int status=0;
    private  String etSearchString="";
    private SearchPopupWindow searchPopupWindow;
    List<SearchCommodityBean.ListBean> dataBeanList=new ArrayList<>();
    private BaseQuickAdapter<SearchCommodityBean.ListBean, BaseViewHolder> canteenadapter;
    private static final String TAG = "SearchGoodsActivity";
    @Override
    protected int getLayoutId() {
        return R.layout.activity_searchgoods;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);

        etSearchString= getIntent().getStringExtra("goodsname");
        if (getIntent().getStringExtra("id")!=null){
            canteenId=  Integer.valueOf(getIntent().getStringExtra("id"));
        }

        etSearch.setText(etSearchString);
        searchCommodity(canteenId,status,etSearchString,1);
        selectCanteenBySchoolId(SPUtil.get(this, IntentKey.ADDRESSID,""));


        checkXiaoliang.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
             if (b){
                 status=1;
                 searchCommodity(canteenId,status,etSearch.getText().toString().trim(),1);

             }else {
                 status=0;
                 searchCommodity(canteenId,status,etSearch.getText().toString().trim(),1);
             }

            }
        });
        checkRenjun.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){
                    status=2;
                    searchCommodity(canteenId,status,etSearch.getText().toString().trim(),1);
                }else {
                    status=0;
                    searchCommodity(canteenId,status,etSearch.getText().toString().trim(),1);
                }
            }
        });

    }

    private void searchCommodity(int canteenId,int status,String commodityName ,int page) {
        EasyHttp.post(this)
                .api(new SearchCommodityApi().setCanteenId(canteenId+"").setSchoolId(SPUtil.get(this,IntentKey.ADDRESSID,"")).setStatus(status+"").setCommodityName(commodityName).setPageNum(page+"").setPageSize("999")).request(new HttpCallback<SearchCommodityBean>(this) {

            @Override
            public void onSucceed(SearchCommodityBean data) {
                if (data.getCode()==0) {
                    dataBeanList.clear();
                    if (data.getList()!=null) {
                        dataBeanList.addAll(data.getList());
                    }
                    if (canteenadapter==null) {
                        canteenadapter = new BaseQuickAdapter<SearchCommodityBean.ListBean, BaseViewHolder>
                                (R.layout.item_search_goods, dataBeanList) {

                            @Override
                            protected void convert(BaseViewHolder baseViewHolder, SearchCommodityBean.ListBean dataBean) {
                                GlideApp.with(getContext()).load(IntentKey.CAR_IMAGE+dataBean.getLogo()).into(((ImageView) baseViewHolder.getView(R.id.img_shop)));
                                baseViewHolder.setText(R.id.tv_shop_name, dataBean.getMerchantName());
                                baseViewHolder.setText(R.id.tv_xiaoshounumber, "销售" + dataBean.getSales() + "份");
                                baseViewHolder.setText(R.id.tv_address, dataBean.getCanteenName());
                                if (dataBean.getCapite()!=null) {
                                    baseViewHolder.setText(R.id.tv_renjunmoney, "人均" + dataBean.getCapite() + "元");
                                }
                                if (dataBean.getStatus()==0){
                                    baseViewHolder.setGone(R.id.tv_status,true);
                                }else {
                                    baseViewHolder.setVisible(R.id.tv_status,true);
                                }
                                if (dataBean.getMerchantActivitys() != null || !dataBean.getMerchantActivitys().isEmpty()) {
                                    if (dataBean.getMerchantActivitys().size() > 0 && dataBean.getMerchantActivitys().size() < 2) {

                                        baseViewHolder.setText(R.id.tv_tag_type1, "满" +BigDecimalUtils.div(dataBean.getMerchantActivitys().get(0).getMeetTheConditions()+"","100",0)  + "减" + BigDecimalUtils.div(dataBean.getMerchantActivitys().get(0).getCreditFor()+"","100",0));
                                        baseViewHolder.setVisible(R.id.tv_tag_type1, true);
                                        baseViewHolder.setVisible(R.id.tv_tag_type2, false);
                                    } else if (dataBean.getMerchantActivitys().size() >= 2) {
                                        baseViewHolder.setText(R.id.tv_tag_type1, "满" +BigDecimalUtils.div(dataBean.getMerchantActivitys().get(0).getMeetTheConditions()+"","100",0)  + "减" + BigDecimalUtils.div(dataBean.getMerchantActivitys().get(0).getCreditFor()+"","100",0));
                                        baseViewHolder.setText(R.id.tv_tag_type1, "满" +BigDecimalUtils.div(dataBean.getMerchantActivitys().get(1).getMeetTheConditions()+"","100",0)  + "减" + BigDecimalUtils.div(dataBean.getMerchantActivitys().get(1).getCreditFor()+"","100",0));
                                        baseViewHolder.setVisible(R.id.tv_tag_type1, true);
                                        baseViewHolder.setVisible(R.id.tv_tag_type2, true);
                                    }
                                } else {
                                    baseViewHolder.setVisible(R.id.tv_tag_type1, false);
                                }

                                RecyclerView rvcommodity = baseViewHolder.getView(R.id.rv_shop);
                                if (dataBean.getCommodity() == null || dataBean.getCommodity().size() == 0) {
                                    baseViewHolder.setGone(R.id.rv_shop, true);
                                } else {
                                    baseViewHolder.setVisible(R.id.rv_shop, true);
                                }
                                rvcommodity.setLayoutManager(new GridLayoutManager(SearchGoodsActivity.this,3));

                                rvcommodity.setAdapter(new BaseQuickAdapter<SearchCommodityBean.ListBean.CommodityBean, BaseViewHolder>(R.layout.item_shop, dataBean.getCommodity()) {
                                    @Override
                                    protected void convert(@NotNull BaseViewHolder chlidViewHolder, SearchCommodityBean.ListBean.CommodityBean bean) {

                                        if (bean.getIsSoldOut()==1){
                                            chlidViewHolder.setVisible(R.id.rl_status,true);

                                        }else {
                                            chlidViewHolder.setVisible(R.id.rl_status,false);
                                        }
                                        GlideApp.with(getContext()).load(IntentKey.CAR_IMAGE+bean.getImg()).into(((ImageView) chlidViewHolder.getView(R.id.imageview)));
                                        chlidViewHolder.setText(R.id.tv_name, bean.getCommodityName());
                                        chlidViewHolder.setText(R.id.tv_price, "¥" + BigDecimalUtils.div(bean.getPrice()+"","100",2));
                                    }


                                });

                                ((BaseQuickAdapter<SearchCommodityBean.ListBean.CommodityBean, BaseViewHolder>) rvcommodity.getAdapter()).setOnItemClickListener((baseQuickAdapter, view, i) -> {

                                    if (!CourseUtils.isNotNullOrEmpty(SPUtil.get(getContext(),IntentKey.USERID,""))){
                                        startActivity(LoginCodeActivity.class);
                                        return;
                                    }
                                    startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id", canteenadapter.getData().get(baseViewHolder.getAbsoluteAdapterPosition()).getMerchantId()+""));

                                });
                            }


                        };
                        View emptyview = View.inflate(SearchGoodsActivity.this, R.layout.empty_emptylayout, null);

                        canteenadapter.setEmptyView(emptyview);

                        rvGoodsSearches.setAdapter(canteenadapter);
                        canteenadapter.setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                                if (!CourseUtils.isNotNullOrEmpty(SPUtil.get(getContext(),IntentKey.USERID,""))){
                                    startActivity(LoginCodeActivity.class);
                                    return;
                                }

                                startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id",dataBeanList.get(position).getMerchantId()+""));
                            }
                        });
                    }else {
                        canteenadapter.notifyDataSetChanged();
                    }
                }
            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });

    }


    private void selectCanteenBySchoolId(String schoolid) {
        EasyHttp.post(this)
                .api(new SelectCanteenBySchoolIdApi().setSchoolid(schoolid)).request(new HttpCallback<SelectCanteenBySchoolBean>(this) {

            @Override
            public void onSucceed(SelectCanteenBySchoolBean data) {
                  if (data.getCode()==0){
                      searchPopupWindow = new SearchPopupWindow(getContext(), data.getList());

                      searchPopupWindow.setOnItemLickenter(new SearchPopupWindow.OnItemLickenter() {
                          @Override
                          public void onTypeClick(int type) {
                              canteenId    =  type;
                              searchCommodity(canteenId,0,etSearchString,1);
                          }
                      });
                  }
            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });


    }
    @OnClick({R.id.image_back, R.id.rl_clear, R.id.title_bar_txt_right,R.id.check_address})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.rl_clear:
                etSearch.setText("");
                rlClear.setVisibility(View.GONE);
                break;
            case R.id.title_bar_txt_right:
                etSearchString=  etSearch.getText().toString().trim();
//                搜索
                searchCommodity(canteenId,status,etSearchString,1);
                break;
            case R.id.check_address:
                if (searchPopupWindow.isShowing()) {
                    searchPopupWindow.dismiss();
                } else {
                    if (searchPopupWindow != null) {
//                        WindowManager.LayoutParams lp = getWindow().getAttributes();
//                        lp.alpha = 0.7f;
//                        getWindow().setAttributes(lp);
                        searchPopupWindow.showAsDropDown(llTop);
                    }
                }
                break;
        }
    }
}
